package com.gmall.console.common;

import com.alibaba.fastjson2.JSON;
import com.gmall.console.base.Result;
import com.gmall.console.common.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: jwt 拦截器
 * @author: Jone
 * @create: 2024-05-31
 */
@Component
@Slf4j
public class JwtValidateInterceptor implements HandlerInterceptor {

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("X-Token");
        log.debug(request.getRequestURI()+"需要验证"+token);

        if(null != token){
            try{
                jwtUtil.parseToken(token);
                log.debug(request.getRequestURI()+"验证通过！");
                return true;
            }catch (Exception ex){
                log.error("拦截器报错，",ex);
            }
        }
        log.debug(request.getRequestURI() + "验证失败，禁止访问！");
        //返回前端
        response.setContentType("application/json;charset=utf-8");
        Result<Object> fail = Result.fail(DataCons.MSG_CODE_201, "jwt无效，请重新登录！");
        response.getWriter().write(JSON.toJSONString(fail));
        return false;
    }
}
